
// pages/bookcontent/bookcontent.js
Page({
  data: {
    bookId: '', // 书籍id
    nowChapterID: 0, // 目前章节id
    bookText: [], // 书籍文本
    title: '', // 书籍标题
    author: '', // 书籍作者
    catalog: [], // 书籍目录
    cover: '', // 书籍封面
    num: 0, // 数据章数
    scrollTop:0,
    scrollArr:[0],
    historyChapterID: 0, // 历史记录ID
    options:"",
    next: false,
    prev: false,
    prevFlag: false, // 上一章按钮显示
    nextFlag: false, // 下一章按钮显示
    panelFlag: false, // 功能面板显示
    miniCatalog: false, // 小目录显示
    setFlag: false, // 设置显示
    themeColor: "#d3c2a4", // 页面默认背景颜色
    fontSize: 20, // 文本字体大小
    bookDetail: {}, // 书籍详情
    bookCatalog: {}, // 书籍目录
    bookCatalogSecond: {}, // 书籍目录2
    bookNewCatalog: [], // 新书籍目录
    defultImg: "https://pic2.zhimg.com/v2-ab9549c7127bef7b692021e83d851f07_1440w.jpg?source=172ae18b", // 默认图
    catalogNum: '1-100', // 目录数
    bookFlag: true, // 显示目录
    defaultCatalog: 0, // 默认目录
    little: false,
    colorList: [
      {
        bgColor: "#f2f2f2",
        checked: true
      },
      {
        bgColor: "#d3c2a4",
        checked: false
      },
      {
        bgColor: "#ceecd4",
        checked: false
      },
      {
        bgColor: "#dcc3c9",
        checked: false
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options);
    // this.setData({options:options})
    this.setData({
      bookId: options.bookId,
      nowChapterID: options.nowChapterID,
    })
  },
  onShow(){
    this.getBookChapter()
    this.getThemeColor()
    this.getfontSize()
    
  },
  // 获取书籍章节
  getBookChapter() {
    // 展示loading效果
    let catalog = []
    wx.showLoading({
      title: '数据加载中...',
    })
    if (!this.data.nowChapterID) {
      wx.request({
        url: 'https://apic.netstart.cn/yunyuedu/reader/book/info.json?source_uuid=' + this.data.bookId,
        method: 'GET',
        success: (res) => { 
          catalog = res.data.data.catalog
          this.setData({
            bookDetail: res.data.data.book,
            bookCatalog: catalog,
            bookCatalogSecond: catalog,
            title: res.data.data.book.title,
            author: res.data.data.book.author,
            cover: res.data.data.book.coverImage
          })
          console.log(res.data.data.book);
          console.log("ahahh",this.data.bookCatalog);
          this.data.bookCatalog.forEach((item) => {
            item.leaf = false
          })
          catalog = catalog.filter((item) => {
            return item.needPay == false
          })
  
          this.setData({
            catalog: catalog,
            nowChapterID: catalog[0].uuid
          })
          console.log(res);
          console.log(this.data.catalog);
        },
        complete: () => {
          this.getminiCatalog()
          this.getBookContent()
        }
      })
    } else {
      wx.request({
        url: 'https://apic.netstart.cn/yunyuedu/reader/book/info.json?source_uuid=' + this.data.bookId,
        method: 'GET',
        success: (res) => {
          catalog = res.data.data.catalog
          this.setData({
            bookDetail: res.data.data.book,
            bookCatalog: catalog,
            bookCatalogSecond: catalog,
            title: res.data.data.book.title,
            author: res.data.data.book.author,
            cover: res.data.data.book.coverImage,
            
          })
          this.data.bookCatalog.forEach((item) => {
            item.leaf = false
          })
          console.log("ahahh",res.data.data);
          catalog = catalog.filter((item) => {
            return item.needPay == false
          })
  
          this.setData({
            catalog: catalog,
            nowChapterID: this.data.nowChapterID
          })
          console.log(res);
        },
        complete: () => {
          this.getminiCatalog()
          this.getBookContent()
        }
      })
    }
  },
  // 获取书籍内容
  getBookContent() {
    wx.showLoading({
      title: '数据加载中...',
    })
    wx.request({
      url: 'https://apic.netstart.cn/yunyuedu/reader/book/content.json?source_uuid=' + this.data.bookId + '&content_uuid=' + this.data.nowChapterID,
      method: 'GET',
      success: (res) => {
        this.setData({
          bookText: res.data.data.content.replace(/<h1>/g,'<h1 class="title">').replace(/<p>/g,'<p class="paragraph" style="font-size: ' + this.data.fontSize +'px;">')
        })
        // console.log(this.data.bookText);
        
      },
      // 隐藏loading效果
      complete: () => {
        let index = this.data.catalog.findIndex((item) => item.uuid == this.data.nowChapterID)
        console.log(index);
        if (index == 0) {
          this.setData({
            prevFlag: false
          })
        } else {
          this.setData({
            prevFlag: true
          })
        }

        if (this.data.next) {
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
          })
        }

        if (this.data.little) {
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
          })
        }

        this.setData({
          next: false,
          little: false,
          nextFlag: true
        })
        wx.hideLoading()
      }
    })
    
    
  },
  // 下一章内容
  getNextContent() {
    let index = this.data.catalog.findIndex((item) => item.uuid == this.data.nowChapterID)

    this.setData({
      nextFlag: false
    })

    if (index < this.data.catalog.length - 1) {
      this.setData({
        nowChapterID: this.data.catalog[index + 1].uuid,
        next: true,
      })
      this.getActive()
      this.getBookContent()
    } else {
      wx.showToast({
        title: '以下章节请付费后观看',
        icon: 'none',
      })
    }

    
  },
  // 上一章内容
  getPrevContent() {
    let index = this.data.catalog.findIndex((item) => item.uuid == this.data.nowChapterID)

    if (index > 0) {
      this.setData({
        nowChapterID: this.data.catalog[index - 1].uuid,
      })
      this.getActive()
      this.getBookContent()
    } else {
      wx.showToast({
        title: '没有上一章了',
        icon: 'none',
      })
    }
  },
  // 打开功能面板
  openPanel() {
    this.setData({
      panelFlag: !this.data.panelFlag,
      setFlag: false
    })
  },
  // 打开小目录
  openCatalog() {
    this.setData({
      miniCatalog: true,
      panelFlag: false

    })
    console.log(this.data.bookDetail);
    console.log(this.data.bookNewCatalog);
    
  },
  // 打开设置
  openSet() {
    this.setData({
      setFlag: true,
      panelFlag: false

    })
  },
  // 更改背景颜色
  changeBgcolor(e) {
    console.log(e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index
    this.data.colorList.forEach((item) => item.checked = false)
    this.data.colorList[index].checked = true
    this.setData({
      colorList: this.data.colorList,
      themeColor: this.data.colorList[index].bgColor
    })
    
  },
  // 获取主体颜色
  getThemeColor() {
    let bgColor = wx.getStorageSync('bgColor')
    this.data.colorList.forEach((item) => item.checked = false)
    let index = this.data.colorList.findIndex((item) => item.bgColor == bgColor.bgColor)
    this.data.colorList[index].checked = true
    this.setData({
      themeColor: bgColor.bgColor,
      colorList: this.data.colorList
    })
  },
  // 字体变小
  reduceSize() {
    
    if (this.data.fontSize == 12) {
      wx.showToast({
        title: '已经是最小了~',
        icon: 'none',
      })
    } else {
      this.setData({
        fontSize: this.data.fontSize -= 1
      })
      this.setData({
        bookText: this.data.bookText.replace(/[0-9]+px/g, this.data.fontSize + 'px')
      })
    }
    
  },

  // 字体变大
  increaseSize() {
    
    if (this.data.fontSize == 30) {
      wx.showToast({
        title: '已经是最大了~',
        icon: 'none',
      })
    } else {
      this.setData({
        fontSize: this.data.fontSize += 1
      })
      this.setData({
        bookText: this.data.bookText.replace(/[0-9]+px/g, this.data.fontSize + 'px')
      })
    }
    
  },

  // 获取字体大小
  getfontSize() {
    if (wx.getStorageSync('fontSize')) {
      this.setData({
        fontSize: wx.getStorageSync('fontSize')
      })
    }
  },

  // 关闭目录
  closeCatalog() {
    this.setData({
      miniCatalog: false
    })
  },

  // 获取小目录数据
  getminiCatalog() {
    // console.log(this.data.bookCatalog);
    // 目录处理函数
    function getCatalog(sum) {
      let newArr = []
      let arr = sum
      function getNewArr(arr) {
        let arr2 = []
        let obj = {}
        if (arr.length > 100) {
            arr.forEach((item,index) => {
            if (index < 100) {
              arr2.push(item)
              obj = {active: false,arr2}
            }
          })
          arr.splice(0,100)
          getNewArr(arr)
        } else {
          arr.forEach((item) => {
              arr2.push(item)
              obj = {active: false,arr2}
          })
        }
        newArr.unshift(obj)
      }
      getNewArr(arr)
      // console.log(newArr);
      return newArr
    }
    
    let arr = this.data.bookCatalog
    this.setData({
      bookNewCatalog: getCatalog(arr)
    })
    console.log("哈哈哈",this.data.bookCatalog);
    this.data.bookNewCatalog[0].active = true
    this.getActive()
    // console.log(this.data.bookNewCatalog);
  },

  // 显示快捷目录
  changeBookFlag() {
    this.setData({
      bookFlag: !this.data.bookFlag
    })
    // console.log(11111);
  },

  // 更换目录
  changePage(e) {
    this.setData({
      defaultCatalog: e.target.dataset.index,
      bookFlag: !this.data.bookFlag,
      catalogNum: (e.target.dataset.index * 100 + 1) + '-' + (e.target.dataset.index * 100 + 100)
    })

    this.data.bookNewCatalog.forEach((item) => {
      item.active = false
    })

    this.data.bookNewCatalog[e.target.dataset.index].active = true

    this.setData({
      bookNewCatalog: this.data.bookNewCatalog
    })
    console.log(e.target.dataset);
    this.getActive()
  },

  // 小目录更换章节
  goContent(e) {
    // console.log(e.currentTarget.dataset);
    if (!e.currentTarget.dataset.vip) {
      this.setData({
        nowChapterID: e.currentTarget.dataset.nowchapterid,
        miniCatalog: false,
        little: true
      })
      this.getActive()
      this.getBookContent()
    } else {
      wx.showToast({
        title: '此章节需要付费观看',
        icon: 'none',
      })
    }
  },

  // 获取高亮章节
  getActive() {
    let index = this.data.bookNewCatalog[0].arr2.findIndex((item) => item.uuid == this.data.nowChapterID)
    this.data.bookNewCatalog[0].arr2.forEach((item) => {
      item.leaf = false
    })
    this.data.bookNewCatalog[0].arr2[index].leaf = true
    
    this.setData({
      bookNewCatalog: this.data.bookNewCatalog
    })
    console.log("1",this.data.catalog);
  },
  
  onHide() {
    
  },

 
  onPullDownRefresh() {

  },

  onUnload(){
    // const m1 = require('../../utils/tools.wxs');
    let hisArr = wx.getStorageSync('historyCatalog') || []
    // 判断此书是否存在历史中
    let date = +new Date()
    if(hisArr.every((item)=>item.bookId!=this.data.bookId)){
      wx.setStorageSync('historyCatalog',[{
        bookId:this.data.bookId,
        historyId:this.data.nowChapterID,
        title: this.data.title,
        author: this.data.author,
        date: date,
        cover: this.data.cover,
        isInShelf: false
      },...hisArr])
    }else{
      let index=hisArr.findIndex((item)=>item.bookId==this.data.bookId)
      hisArr.splice(index,1)

      wx.setStorageSync('historyCatalog',[{
        bookId:this.data.bookId,
        historyId:this.data.nowChapterID,
        title: this.data.title,
        author: this.data.author,
        date: date,
        cover: this.data.cover,
        isInShelf: false
      },...hisArr])
      // hisArr[index].historyId=this.data.nowChapterID
      // wx.setStorageSync('historyCatalog',hisArr)
    }
    console.log("-------",this.data.title,this.data.author);
    wx.setStorageSync('bgColor', {bgColor: this.data.themeColor})
    wx.setStorageSync('fontSize', this.data.fontSize)
  },

  onShareAppMessage() {

  },
})